﻿CREATE FUNCTION PtpStatus(
	@AccountNumber varchar(10),
	@PaymentOriginal money,
	@PtpDate datetime,
	@PtpAgent varchar(64),
	@DaysTolerance tinyint = 1,
	@PaymentTolerance tinyint = .75
)RETURNS tinyint
AS BEGIN

DECLARE @BD int
SET @BD = CASE DATEPART(dw,@PtpDate)
					WHEN 5 THEN 3
					WHEN 6 THEN 2
					ELSE 1
END
SET @PtpDate = dateadd(dd,@DaysTolerance,@PtpDate)

IF @PtpDate > GETDATE() RETURN 0

DECLARE @NoteDate datetime

SELECT     TOP (1) @NoteDate = CreatedDate
FROM         vantage.t_Note
WHERE     (AccountNumber = @AccountNumber) AND (CreatedDate < @PtpDate) AND (CreatedUser = @PtpAgent)
ORDER BY CreatedDate DESC

DECLARE	@PaymentMade money

SELECT     @PaymentMade = PaymentAmount
FROM         Vantage_In..Target_Payment
WHERE     PaymentEffectiveDate BETWEEN dateadd(dd,1,@NoteDate) AND @PtpDate

IF @PaymentMade IS NULL RETURN 3

IF @PaymentMade >= @PaymentOriginal * @PaymentTolerance RETURN 1

RETURN 2
END


